/** @odoo-module **/
import { registry } from "@web/core/registry";
import { useService, useBus } from "@web/core/utils/hooks";
import { EventBus, onWillStart, onWillUpdateProps, status, useComponent } from "@odoo/owl";
import { rpc } from "@web/core/network/rpc";
import { Component, useEffect, useExternalListener, useRef,onMounted  } from "@odoo/owl";
 
import { Dialog } from "@web/core/dialog/dialog";
function flattenObject(obj, prefix = "") {
    const result = {};
    for (const key in obj) {
      const value = obj[key];
      const newKey = prefix ? `${prefix}_${key}` : key;

      if (
        typeof value === "object" &&
        value !== null &&
        !Array.isArray(value)
      ) {
        if ("id" in value || "display_name" in value) {
          if ("id" in value) result[`${newKey}_id`] = value.id;
          if ("display_name" in value)
            result[`${newKey}_display_name`] = value.display_name; // ← 修改点
        } else {
          Object.assign(result, flattenObject(value, newKey));
        }
      } else if (!Array.isArray(value)) {
        result[newKey] = value;
      }
    }
    return result;
  }
  function flattenArrayField(arr) {
    return arr.map((item) => {
      const row = {};
      for (const key in item) {
        const value = item[key];

        if (Array.isArray(value)) {
          continue; // 跳过二级数组
        } else if (typeof value === "object" && value !== null) {
          Object.assign(row, flattenSingleLevelObject(value, key));
        } else {
          row[key] = value;
        }
      }
      return row;
    });
  }
  function flattenSingleLevelObject(obj, prefix) {
    const result = {};
    for (const key in obj) {
      const value = obj[key];
      if (
        typeof value !== "object" ||
        value === null ||
        Array.isArray(value)
      ) {
        result[`${prefix}_${key}`] = value;
      }
    }
    return result;
  }
  function transformData(data) {
    const result = {};
    const firstObj = data[0];

    for (const key in firstObj) {
      const value = firstObj[key];

      if (Array.isArray(value)) {
        result[key] = flattenArrayField(value);
      } else if (typeof value === "object" && value !== null) {
        if ("id" in value || "display_name" in value) {
          if ("id" in value) result[`${key}_id`] = value.id;
          if ("display_name" in value)
            result[`${key}_display_name`] = value.display_name; // ← 修改点
        } else {
          Object.assign(result, flattenObject(value, key));
        }
      } else {
        result[key] = value;
      }
    }

    return result;
  }
  function transformFields(fields) {
    const normalFields = [];
    const tableMap = {};

    function getTopParent(field) {
      while (field.parent) {
        field = field.parent;
      }
      return field;
    }

    for (const field of fields) {
      const id = field.id;

      // 普通字段（无 '/' 且类型不是 one2many/many2many）
      if (
        !id.includes("/") &&
        (!field.field_type || !field.field_type.includes("2many"))
      ) {
        normalFields.push({
          tid: `configModule.${id}`,
          title: field.string.split("/").pop(),
          field: id,

          data: "",
          type: "text",
        });
      }
    }

    for (const field of fields) {
      const id = field.id;

      // 嵌套字段（带 '/'）
      if (id.includes("/")) {
        const parts = id.split("/");
        const lastPart = parts[parts.length - 1];

        // 查找最顶层 parent，如果是 one2many 或 many2many，属于表格字段
        if (field.parent) {
          const top = getTopParent(field);
          const tableId = top.id;

          if (["one2many", "many2many"].includes(top.field_type)) {
            tableMap[tableId] = tableMap[tableId] || {
              tid: `configModule.${tableId}`,
              field: tableId,
              title: top.string,
              type: "table",
              editable: true,
              columnDisplayEditable: true,
              columnDisplayIndexEditable: true,
              columnTitleEditable: true,
              columnResizable: true,
              columnAlignEditable: true,
              columns: [[]],
            };

            //const fieldKey = id.replace(/\//g, "_").replace(/\./g, "");
            const parts = id.split("/");
            const fieldKey = parts.slice(1).join("_"); // 去掉顶层字段（如 order_line）
            const fieldTitle = field.string.split("/").pop();

            tableMap[tableId].columns[0].push({
              title: fieldTitle,
              align: "center",
              field: fieldKey,
              width: 100,
            });
          } else {
            // 顶层不是 one2many 表格字段，直接作为普通字段处理
            normalFields.push({
              tid: `configModule.${id.replace(/\//g, "_")}`,
              title: field.string.split("/").pop(),
              field: id.replace(/\//g, "_"),
              data: "",
              type: "text",
            });
          }
        } else {
          // 无 parent 直接保留为普通字段
          normalFields.push({
            tid: `configModule.${id.replace(/\//g, "_")}`,
            title: field.string.split("/").pop(),
            field: id.replace(/\//g, "_"),
            data: "",
            type: "text",
          });
        }
      }
    }

    return [...normalFields, ...Object.values(tableMap)];
  }

  // 构建 specification
  function buildSpecification(fields) {
    const spec = {};

    for (const field of fields) {
      const path = field.id.split("/");
      if (path.length === 1) {
        // 顶层字段
        spec[field.id] = {};
      } else {
        // 嵌套字段
        const [parent, child] = path;
        if (!spec[parent]) {
          spec[parent] = { fields: {} };
        }
        if (!spec[parent].fields) {
          spec[parent].fields = {};
        }
        spec[parent].fields[child] = {};
      }
    }

    return spec;
  }
export class hiprintDesign extends Component {
    static template = "hiprintDesign";
    static components = { Dialog };
    static props = ["*"];
    setup() {
      
        onMounted(async () => {
            console.log(this.__owl__.app.env.a);
           if (!window.a==true) {
            try {
                let result = await this.jiazaijs1("/hiwprint/static/src/hiprint/plugins/jq-3.31.js");
                result = await this.jiazaijs1("/hiwprint/static/src/hiprint/content/bootstrap.min.js");
                result = await this.jiazaijs1("/hiwprint/static/src/hiprint/polyfill.min.js");
                result = await this.jiazaijs1("/hiwprint/static/src/hiprint/plugins/jquery.minicolors.min.js");
             result = await this.jiazaijs1("/hiwprint/static/src/hiprint/plugins/JsBarcode.all.min.js");
             result = await this.jiazaijs1("/hiwprint/static/src/hiprint/plugins/qrcode.js");
             result = await this.jiazaijs1("/hiwprint/static/src/hiprint/hiprint.bundle.js");
             result = await this.jiazaijs1("/hiwprint/static/src/hiprint/plugins/jquery.hiwprint.js");
             window.a=true;                      
            } catch (err) {
                console.error(err);
            }
           }
           await this.jiazaijs1("/hiwprint/static/src/hiprint/hiprint.bundle.js");
           function randomString(length = 8) {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for (let i = 0; i < length; i++) {
              result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return result;
          }
          let suiji=randomString();
           
        
           let cfdt= transformFields(this.props.ziduans);
           console.log(cfdt);
           this.configData =cfdt;
        
        
          let mbsj=this.props.moban;
           this.configPrintJson= mbsj;
           var configElementTypeProvider = (function () {
            return function (options) {
              var addElementTypes = function (context) {
                
                context.addPrintElementTypes(suiji, [
                  new hiprint.PrintElementTypeGroup("业务数据", cfdt),
    
                  new hiprint.PrintElementTypeGroup("辅助", [
                    {
                      tid: "configModule.hline",
                      title: "横线",
                      type: "hline",
                    },
                    {
                      tid: "configModule.vline",
                      title: "竖线",
                      type: "vline",
                    },
                    {
                      tid: "configModule.rect",
                      title: "矩形",
                      type: "rect",
                    },
                    {
                      tid: "testModule.oval",
                      title: "椭圆",
                      type: "oval",
                    },
                  ]),
                ]);
              };
    
              return {
                addElementTypes: addElementTypes,
              };
            };
          })();
          hiprint.init({
            providers: [new configElementTypeProvider()],
          });
          $(".hiprintEpContainer").off().empty();
          hiprint.PrintElementTypeManager.build(
            ".hiprintEpContainer",
            suiji
          );
         let designer = new hiprint.PrintTemplate({
            template:mbsj,
            settingContainer: "#printElementOptionSetting",
          });
          designer.design("#printTemplate");
          this.designer = designer;


        });
    }
    async queren2(){
        this.props.close();
         this.props.queren1(this.designer.getJsonTid());

    }
    async jiazaijs1(url) {
        return new Promise((resolve, reject) => {
          const script = document.createElement('script');
          script.src = url;
          script.type = 'text/javascript';
          script.onload = () => resolve(`Script loaded: ${url}`);
          script.onerror = () => reject(new Error(`Failed to load script: ${url}`));
          document.head.appendChild(script);
          return script;
        });
      }
    
}